<template>
  <div class="cash-bank-report">
    <!-- 顶部筛选区 -->
    <div class="filter-section">
      <el-form :model="filter" inline>
        <!-- 日期范围 -->
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="filter.dateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <!-- 账户选择 -->
        <el-form-item label="账户">
          <el-select
            v-model="filter.accountId"
            placeholder="请选择账户"
            clearable
          >
            <el-option
              v-for="account in accountOptions"
              :key="account.id"
              :label="account.name"
              :value="account.id"
            />
          </el-select>
        </el-form-item>

        <!-- 业务类型 -->
        <el-form-item label="业务类型">
          <el-select
            v-model="filter.bizType"
            placeholder="请选择业务类型"
            clearable
          >
            <el-option
              v-for="item in bizTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 往来单位 -->
        <el-form-item label="往来单位">
          <el-input
            v-model="filter.unit"
            placeholder="请输入往来单位"
            clearable
          />
        </el-form-item>

        <!-- 查询按钮 -->
        <el-form-item>
          <el-button type="primary" @click="queryData">查询</el-button>
          <el-button type="success" @click="exportExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格数据展示 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      show-summary
      :summary-method="getSummaries"
      stripe
    >
      <el-table-column label="账户编号" prop="accountCode" width="100" />
      <el-table-column label="账户名称" prop="accountName" width="120" />
      <el-table-column label="日期" prop="date" width="120" />
      <el-table-column label="单据编号" prop="docNo" width="150" />
      <el-table-column label="业务类型" prop="bizType" width="120" />
      <el-table-column
        label="收入"
        prop="income"
        align="right"
        width="100"
        :formatter="currencyFormatter"
      />
      <el-table-column
        label="支出"
        prop="expense"
        align="right"
        width="100"
        :formatter="currencyFormatter"
      />
      <el-table-column
        label="账户余额"
        prop="balance"
        align="right"
        width="120"
        :formatter="currencyFormatter"
      />
      <el-table-column label="往来单位" prop="unit" width="150" />
      <el-table-column label="收/付款人" prop="payer" width="150" />
      <el-table-column label="备注" prop="remark" width="200" />
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";

// 筛选条件
const filter = reactive({
  dateRange: [new Date("2025-06-01"), new Date("2025-06-26")],
  accountId: "",
  bizType: "",
  unit: "",
});

// 账户选项
const accountOptions = ref([
  { id: "1001", name: "现金" },
  { id: "1002", name: "银行存款" },
  { id: "1003", name: "微信支付" },
  { id: "999999", name: "支付宝" },
]);

// 业务类型选项
const bizTypeOptions = ref([
  { value: "initial", label: "期初余额" },
  { value: "sales", label: "销售" },
  { value: "purchase", label: "采购" },
  { value: "receipt", label: "收款" },
  { value: "payment", label: "付款" },
  { value: "transfer", label: "转账" },
]);

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 初始化加载数据
onMounted(() => {
  queryData();
});

// 查询数据
const queryData = () => {
  console.log("查询参数:", filter);

  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    const mockData = generateMockData(20);
    tableData.value = mockData;
    total.value = mockData.length;
    ElMessage.success("查询成功");
  }, 500);
};

// 生成模拟数据
const generateMockData = (count) => {
  const accounts = [
    { code: "1001", name: "现金" },
    { code: "1002", name: "银行存款" },
    { code: "1003", name: "微信支付" },
    { code: "999999", name: "支付宝" },
  ];

  const bizTypes = [
    { value: "initial", label: "期初余额" },
    { value: "sales", label: "销售" },
    { value: "purchase", label: "采购" },
    { value: "receipt", label: "收款" },
    { value: "payment", label: "付款" },
    { value: "transfer", label: "转账" },
  ];

  const units = ["蓝天食品", "小蝶食品", "中通快递", "韵达快递", "圆通速递"];
  const payers = ["老板", "财务-玲", "采购-小陈"];

  let balance = 100000; // 初始余额

  return Array.from({ length: count }).map((_, index) => {
    const account = accounts[index % accounts.length];
    const isInitial = index === 0 || index % 5 === 0; // 每5条记录插入一条期初余额

    const income = isInitial ? 0 : Math.random() * 10000;
    const expense = isInitial ? 0 : Math.random() * 5000;

    balance = isInitial
      ? 86923.74 + Math.random() * 1000 // 模拟不同账户的期初余额
      : balance + income - expense;

    const bizType = isInitial
      ? bizTypes[0]
      : bizTypes[Math.floor(Math.random() * (bizTypes.length - 1)) + 1];

    return {
      id: index + 1,
      accountCode: account.code,
      accountName: account.name,
      date: isInitial ? "" : `2025-06-${Math.floor(Math.random() * 26) + 1}`,
      docNo: isInitial
        ? ""
        : `D${Math.floor(Math.random() * 1000000)
            .toString()
            .padStart(6, "0")}`,
      bizType: bizType.label,
      income: isInitial ? 0 : income,
      expense: isInitial ? 0 : expense,
      balance: balance,
      unit: isInitial ? "" : units[Math.floor(Math.random() * units.length)],
      payer: isInitial ? "" : payers[Math.floor(Math.random() * payers.length)],
      remark: isInitial ? "" : "业务备注信息",
    };
  });
};

// 格式化货币
const currencyFormatter = (row, column, value) => {
  return value ? `¥${value.toFixed(2)}` : "¥0.00";
};

// 计算合计行
const getSummaries = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }

    if (["income", "expense", "balance"].includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => isNaN(value))) {
        sums[index] = `¥${values
          .reduce((prev, curr) => prev + curr, 0)
          .toFixed(2)}`;
      } else {
        sums[index] = "¥0.00";
      }
    }
  });
  return sums;
};

// 分页事件
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  queryData();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  queryData();
};

// 导出Excel
const exportExcel = () => {
  ElMessage.info("导出功能开发中...");
};
</script>

<style scoped>
.cash-bank-report {
  padding: 24px;
  background-color: #fff;
}

.filter-section {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  text-align: right;
}

/* 合计行样式 */
.el-table__footer-row {
  background-color: #fff9e6;
  font-weight: bold;
}
</style>